<?php

namespace App\Exception\Handler;

use App\Exception\AppReturnException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

class AppReturnExceptionHandler extends ExceptionHandler
{

    public function __construct(protected StdoutLoggerInterface $logger)
    {
    }

    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        // 如果是自定义异常，返回对应的错误信息
        if ($throwable instanceof AppReturnException) {
            // 阻止异常冒泡
            $this->stopPropagation();
            return $response->withStatus(500)->withBody(new SwooleStream($throwable->getMessage()));
        }
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}